//
//  XMReportViewController.m
//  XunMi
//
//  Created by MacBook on 2024/2/27.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMDynamicUploadViewController.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import "XMGridViewFlowLayout.h"
#import "XMUploadCell.h"
#import <Photos/Photos.h>

static NSInteger kMaxNumber = 300;
static NSInteger kMaxVideoLength = 30;
static NSInteger kMaxImageWidth = 10000;

@interface XMDynamicUploadViewController () <UITextViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, TZImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *countLa;
@property (weak, nonatomic) IBOutlet UIView *bgV;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) XMGridViewFlowLayout *layout;
@property (nonatomic, strong) NSMutableArray *selectedPhotos;
@property (nonatomic, strong) NSMutableArray *selectedAssets;
@property (nonatomic, assign) BOOL isSelectOriginalPhoto;
@end

@implementation XMDynamicUploadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navLeft2Btn setTitle:@"发布动态" forState:UIControlStateNormal];
    [self.navRightBtn setTitle:@"发布" forState:UIControlStateNormal];
    [self.navRightBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(66, 32));
    }];
    [self.navRightBtn setBackgroundColor:kAppMainColor];
    [self.navRightBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [self.navRightBtn addTarget:self action:@selector(upload) forControlEvents:UIControlEventTouchUpInside];
    
    kCornerRadius(self.navRightBtn, 16, 0, UIColor.clearColor);
    kCornerRadius(self.bgV, 10, 0, UIColor.clearColor);
    
    self.textView.placeholder = @"发个动态，选个最抢眼的照片，让你更容易被发现哦～";
    self.textView.placeholderColor = kHEX(@"9A9A9A");
    self.textView.delegate = self;
    
    self.layout = [[XMGridViewFlowLayout alloc] init];
    
    self.layout.itemSize = CGSizeMake((kScreenWidth - 70) / 4.0, (kScreenWidth - 70) / 4.0);
    
    self.layout.minimumInteritemSpacing = 10;
    self.layout.minimumLineSpacing = 10;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
    self.collectionView.backgroundColor = UIColor.clearColor;
    self.collectionView.alwaysBounceVertical = YES;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[XMUploadCell class] forCellWithReuseIdentifier:kStringFromClass(XMUploadCell)];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgV.mas_bottom).offset(20);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(kScreenWidth - 40);
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.selectedPhotos.count >= 9) {
        return self.selectedPhotos.count;
    }
    for (PHAsset *asset in self.selectedAssets) {
        if (asset.mediaType == PHAssetMediaTypeVideo) {
            return self.selectedPhotos.count;
        }
    }
    return self.selectedPhotos.count + 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XMUploadCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kStringFromClass(XMUploadCell) forIndexPath:indexPath];
    cell.videoImageView.hidden = YES;
    cell.timeLa.hidden = YES;
    if (indexPath.item == self.selectedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"xm_upload_add"];
        cell.deleteBtn.hidden = YES;
        cell.timeLa.hidden = YES;
    } else {
        cell.imageView.image = self.selectedPhotos[indexPath.item];
        cell.asset = self.selectedAssets[indexPath.item];
        cell.deleteBtn.hidden = NO;
    }
    cell.deleteBtn.tag = indexPath.item;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == self.selectedPhotos.count) {
        [self chooseImageAndVideo];
    } else {
        PHAsset *asset = self.selectedAssets[indexPath.item];
        BOOL isVideo = NO;
        isVideo = asset.mediaType == PHAssetMediaTypeVideo;
        if ([[asset valueForKey:@"filename"] containsString:@"GIF"]) {
            TZGifPhotoPreviewController *vc = [[TZGifPhotoPreviewController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypePhotoGif timeLength:@""];
            vc.model = model;
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:vc animated:YES completion:nil];
        } else if (isVideo) {
            TZVideoPlayerController *vc = [[TZVideoPlayerController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypeVideo timeLength:kStringFormat(@"%.0f", asset.duration)];
            vc.model = model;
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:vc animated:YES completion:nil];
        } else {
            [self previewPhotoWithIndex:indexPath.item];
        }
    }
}

- (void)chooseImageAndVideo {
    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    imagePicker.isSelectOriginalPhoto = NO;
    imagePicker.selectedAssets = self.selectedAssets;
    imagePicker.videoMaximumDuration = kMaxVideoLength;
    [imagePicker setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    imagePicker.navigationBar.barTintColor = UIColor.whiteColor;
    imagePicker.oKButtonTitleColorNormal = kAppMainColor;
    imagePicker.oKButtonTitleColorDisabled = kAppMainColor;
    imagePicker.barItemTextColor = UIColor.blackColor;
    imagePicker.navigationBar.translucent = NO;
    [imagePicker.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];
    imagePicker.navigationBar.tintColor = UIColor.blackColor;
    if (@available(iOS 13.0, *)) {
        UINavigationBarAppearance *barAppearance = [[UINavigationBarAppearance alloc] init];
        barAppearance.backgroundColor = imagePicker.navigationBar.barTintColor;
        barAppearance.titleTextAttributes = imagePicker.navigationBar.titleTextAttributes;
        imagePicker.navigationBar.standardAppearance = barAppearance;
        imagePicker.navigationBar.scrollEdgeAppearance = barAppearance;
    }
    imagePicker.iconThemeColor = kAppMainColor;
    imagePicker.showPhotoCannotSelectLayer = YES;
    imagePicker.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    [imagePicker setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [previewButton setTitleColor:kAppMainColor forState:UIControlStateNormal];
        [originalPhotoButton setImage:kGetImage(@"ic_dyn_origin_s") forState:UIControlStateSelected];
    }];
    [imagePicker setNavLeftBarButtonSettingBlock:^(UIButton *leftButton) {
        [leftButton setImage:[UIImage imageNamed:@"ic_arrow_left_black"] forState:UIControlStateNormal];
        [leftButton setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 20)];
    }];
    imagePicker.statusBarStyle = UIStatusBarStyleDefault;
    imagePicker.showSelectedIndex = YES;
    imagePicker.sortAscendingByModificationDate = NO;
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePicker animated:YES completion:nil];
}
- (void)previewPhotoWithIndex:(NSInteger)index {
    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithSelectedAssets:self.selectedAssets selectedPhotos:self.selectedPhotos index:index];
    imagePicker.isSelectOriginalPhoto = self.isSelectOriginalPhoto;
    imagePicker.maxImagesCount = 9;
    imagePicker.allowPickingOriginalPhoto = YES;
    imagePicker.oKButtonTitleColorNormal = kAppMainColor;
    imagePicker.oKButtonTitleColorDisabled = kAppMainColor;
    imagePicker.iconThemeColor = kAppMainColor;
    imagePicker.showSelectedIndex = YES;
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePicker.autoDismiss = YES;
    XMWeakSelf(self);
    [imagePicker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        XMStrongSelf(self);
        self.selectedPhotos = [NSMutableArray arrayWithArray:photos];
        self.selectedAssets = [NSMutableArray arrayWithArray:assets];
        self.isSelectOriginalPhoto = isSelectOriginalPhoto;
        [self.collectionView reloadData];
    }];
    [self presentViewController:imagePicker animated:YES completion:nil];
}

#pragma mark - LxGridViewDataSource
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.item < self.selectedPhotos.count;
}
- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath canMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    return (sourceIndexPath.item < self.selectedPhotos.count && destinationIndexPath.item < self.selectedPhotos.count);
}
- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    UIImage *image = self.selectedPhotos[sourceIndexPath.item];
    [self.selectedPhotos removeObjectAtIndex:sourceIndexPath.item];
    [self.selectedPhotos insertObject:image atIndex:destinationIndexPath.item];
    id asset = self.selectedAssets[sourceIndexPath.item];
    [self.selectedAssets removeObjectAtIndex:sourceIndexPath.item];
    [self.selectedAssets insertObject:asset atIndex:destinationIndexPath.item];
    [self.collectionView reloadData];
}
#pragma mark - TZImagePickerControllerDelegate
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    self.selectedPhotos = [NSMutableArray arrayWithArray:photos];
    self.selectedAssets = [NSMutableArray arrayWithArray:assets];
    self.isSelectOriginalPhoto = isSelectOriginalPhoto;
    [self.collectionView reloadData];
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
    self.selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
    self.selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    [self.collectionView reloadData];
}
- (BOOL)isAssetCanBeSelected:(PHAsset *)asset {
    switch (asset.mediaType) {
        case PHAssetMediaTypeVideo: {
            NSTimeInterval duration = floor(asset.duration);
            if (duration > kMaxVideoLength) {
                [MBProgressHUD showHUDMsg:kStringFormat(@"不支持选择超过%ld秒的视频", kMaxVideoLength) toView:nil];
                return NO;
            }
            return YES;
        } break;
        case PHAssetMediaTypeImage: {
            return YES;
        } break;
        case PHAssetMediaTypeAudio:
            return NO;
            break;
        case PHAssetMediaTypeUnknown:
            return NO;
            break;
        default:
            return YES;
            break;
    }
}
#pragma mark - Actions
- (void)upload {
    if (self.textView.text.length == 0 &&
        self.selectedPhotos.count == 0 &&
        self.selectedAssets.count == 0) {
        [MBProgressHUD showHUDMsg:@"动态内容不能为空哦!" toView:nil];
        return;
    }
    [self.textView resignFirstResponder];
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    if (self.selectedPhotos.count > 0 && self.selectedAssets.count > 0) {
        __block BOOL isVideo = NO;
        [self.selectedAssets enumerateObjectsUsingBlock:^(PHAsset *_Nonnull asset, NSUInteger idx, BOOL *_Nonnull stop) {
            if (asset.mediaType == PHAssetMediaTypeVideo) {
                isVideo = YES;
                *stop = YES;
                return;
            }
        }];
        if (isVideo) {
            [self uploadVideo];
        } else {
            [self uploadImages];
        }
    } else {
        [self publishDynamicText:self.textView.text imageJson:@"" videoJson:@""];
        
    }
}

- (void)uploadVideo {
    [[TZImageManager manager] getVideoOutputPathWithAsset:self.selectedAssets[0]
                                               presetName:AVAssetExportPresetHighestQuality
                                                  success:^(NSString *outputPath) {
        XMLog(@"视频导出到本地完成,沙盒路径为:%@", outputPath);
        [XMUploadManager.sharedInstance uploadWithFilePath:outputPath type:(XMUploadTypeVideo) person_id:kUserModel.person_id complete:^(XMUploadResultModel * _Nonnull result) {
            if (result.success) {
                NSString *videoJson = [[XMUploadResultModel paramDic:result fileType:@"3"] jsonStringEncoded];
                [self publishDynamicText:self.textView.text imageJson:@"" videoJson:videoJson];
            } else {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showHUDMsg:@"视频上传失败请重试" toView:nil];
            }
            
        }];
    } failure:^(NSString *errorMessage, NSError *error) {
        XMLog(@"视频导出失败:%@,error:%@", errorMessage, error);
    }];
}

- (void)uploadImages {
    __block NSMutableArray *imageParams = [NSMutableArray array];
    [XMUploadManager.sharedInstance uploadImageArray:self.selectedPhotos person_id:kUserModel.person_id complete:^(NSMutableArray<XMUploadResultModel *> * _Nonnull array) {
        [array enumerateObjectsUsingBlock:^(XMUploadResultModel *_Nonnull model, NSUInteger idx, BOOL *_Nonnull stop) {
            [imageParams addObject:[XMUploadResultModel paramDic:model fileType:@"1"]];
        }];
        NSString *imageJson = [imageParams jsonStringEncoded];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self publishDynamicText:self.textView.text imageJson:imageJson videoJson:@""];
        });
    }];
}

- (void)publishDynamicText:(NSString *)text imageJson:(NSString *)imageJson videoJson:(NSString *)videoJson {
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setObject:[NSString xm_stringNoNullWith:[NSString handleUploadText:text]] forKey:@"title"];
    [dic setObject:[NSString xm_stringNoNullWith:imageJson] forKey:@"image"];
    [dic setObject:[NSString xm_stringNoNullWith:videoJson] forKey:@"video"];
    [YHNetworkManager.sharedInstance postWithUrl:@"api/dynamic/create" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showHUDMsg:tip.message toView:nil];
            [kNotificationCenter postNotificationName:@"dynamic_refresh" object:nil];
            [self backAction];
        }
    }];
}

- (void)deleteBtnClik:(UIButton *)sender {
    if ([self collectionView:self.collectionView numberOfItemsInSection:0] <= self.selectedPhotos.count) {
        [self.selectedPhotos removeObjectAtIndex:sender.tag];
        [self.selectedAssets removeObjectAtIndex:sender.tag];
        [self.collectionView reloadData];
        return;
    }
    [self.selectedPhotos removeObjectAtIndex:sender.tag];
    [self.selectedAssets removeObjectAtIndex:sender.tag];
    [self.collectionView
     performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    }
     completion:^(BOOL finished) {
        [self.collectionView reloadData];
    }];
}

- (void)textViewDidChange:(UITextView *)textView {
    // 处理字符变化的逻辑
    if (textView.text.length > kMaxNumber) {
        textView.text = [textView.text substringWithRange:NSMakeRange(0, kMaxNumber)];
    }
    self.countLa.text = kStringFormat(@"%ld/%ld", textView.text.length, kMaxNumber);
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

@end
